<?php

namespace App\Models\Traits;

use App\Models\Common\OperateLog;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Facades\Auth;

trait HasOperateLog
{
    public function operateLogs() : MorphMany
    {
        return $this->morphMany(OperateLog::class, 'operable');
    }

    public function saveOperateLog($type, $content)
    {
        $typeStr = trans('global.options.operate_type.' . $type);
        $user = Auth::user() ?? null;
        $operateContent = '';
        if (!is_string($content)) {
            foreach ($content as $key => $item) {
                $item = is_array($item) ? json_encode($item, JSON_UNESCAPED_UNICODE) : $item;
                $operateContent .= $key . ':' . $item . ';';
            }
        } else {
            $operateContent = $content;
        }
        $this->operateLogs()->create([
            'username' => @$user ? ($user->name ?: 'user_' . $user->id) : 'system',
            'user_id' => @$user ? $user->id : 0,
            'content' => $typeStr . ':' . $operateContent,
        ]);
    }
}
